<template>
  <div class="register-container">
    <div class="overlay" v-if="show_cover"></div>
    <div class="register-card">
      <h1>{{ title }}</h1>
      <div class="input-group">
        <div v-for="(field, index) in fields" :key="index" class="form-group">
          <label :for="field.id">{{ field.label }}</label>
          <div class="input-wrapper">
            <input :type="field.type === 'password' ? (showPassword ? 'text' : 'password') : field.type" 
                   :id="field.id" 
                   v-model="form[field.id]" 
                   :placeholder="field.placeholder"
                   autocomplete="off"
                   @input="validateField(field)" />
            <button v-if="field.type === 'password'" 
                    type="button" 
                    class="toggle-password" 
                    @click="togglePasswordVisibility">
              {{ showPassword ? '隐藏' : '显示' }}
            </button>
          </div>
          <span v-if="errors[field.id]" class="error">{{ errors[field.id] }}</span>
        </div>

        <div class="button-group">
          <button v-for="(button, index) in buttons" :key="index" class="register-btn"
            @click="handleButtonClick(button)">
            {{ button.text }}
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { reactive, defineEmits, defineProps, ref } from 'vue';
import { warning } from '../../static/js/alert.js';

const props = defineProps({
  show_cover: {
    type: Boolean,
    default: false,
  },
  title: {
    type: String,
    default: '注册',
  },
  buttons: {
    type: Array,
    required: true,
    validator: (value) => {
      return value.every((button) => {
        return button.text && button.action && (button.requiresValidation === undefined || typeof button.requiresValidation === 'boolean');
      });
    },
  },
  fields: {
    type: Array,
    required: true,
    validator: (value) => {
      return value.every((field) => {
        return (
          field.id &&
          field.label &&
          field.type &&
          field.placeholder &&
          field.validation
        );
      });
    },
  },
});

const emit = defineEmits(['handleSubmit']);

const showPassword = ref(false);

function togglePasswordVisibility() {
  showPassword.value = !showPassword.value;
}

function handleButtonClick(button) {
  // 判断按钮是否需要表单验证
  if (button.requiresValidation === undefined || button.requiresValidation) {
    // 验证表单
    if (!validateForm()) {
      warning("格式错误!");
      return;
    }

    // 检查表单是否为空
    if (isFormEmpty()) {
      warning("表单信息不完整!");
      return;
    }
  }

  // 触发对应的按钮操作事件
  emit(button.action, form);
}

const validateForm = () => {
  let isValid = true;

  props.fields.forEach((field) => {
    // 如果某字段验证失败，设置总体验证为失败
    if (!validateField(field)) {
      isValid = false;
    }
  });

  return isValid;
};

const validateField = (field) => {
  const value = form[field.id];
  const { validation } = field;

  // 必填项验证
  if (validation.required && !value) {
    errors[field.id] = "该字段为必填项";
    return false;
  }

  // 最小长度验证
  if (validation.minLength && value.length < validation.minLength) {
    errors[field.id] = `至少需要${validation.minLength}非常用个字符`;
    return false;
  }

  // 最大长度验证
  if (validation.maxLength && value.length > validation.maxLength) {
    errors[field.id] = `最多只能有${validation.maxLength}个字符`;
    return false;
  }
  
  // 正则表达式验证
  if (validation.pattern && !new RegExp(validation.pattern).test(value)) {
    errors[field.id] = validation.message || "输入格式不正确";
    return false;
  }

  // 清空错误信息
  errors[field.id] = "";
  return true;
};

const form = reactive({});
const errors = reactive({});

props.fields.forEach((field) => {
  form[field.id] = '';
  errors[field.id] = '';
});

const isFormEmpty = () => {
  return Object.values(form).some(value => value === '');
};
</script>

<style scoped>
/* 背景渐变 */
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  width: 100vw;
  padding: 20px;
  position: relative; /* For overlay positioning */
}

/* 遮盖层样式 */
.overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 1;
  pointer-events: none; /* Ensure the overlay doesn't block interactions */
}

/* 卡片样式 */
.register-card {
  background: white;
  padding: 40px;
  border-radius: 15px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.2);
  width: 100%;
  max-width: 400px;
  animation: fadeIn 0.5s ease-in-out;
  position: relative; /* For overlay positioning */
  z-index: 2;
}

/* 标题样式 */
h1 {
  text-align: center;
  margin-bottom: 20px;
  font-size: 24px;
  color: #333;
  font-weight: 600;
}

/* 输入组样式 */
.input-group {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

/* 表单组样式 */
.form-group {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

/* 标签样式 */
label {
  font-weight: 500;
  color: #555;
  font-size: 14px;
}

/* 输入框样式 */
input {
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 8px;
  font-size: 14px;
  transition: border-color 0.3s ease, box-shadow 0.3s ease;
  width: 100%;
}

input:focus {
  border-color: #6a11cb;
  box-shadow: 0 0 8px rgba(106, 17, 203, 0.3);
  outline: none;
}

/* 输入框包裹层 */
.input-wrapper {
  position: relative;
}

/* 切换密码可见性按钮 */
.toggle-password {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  background: none;
  border: none;
  color: #6a11cb;
  cursor: pointer;
  font-size: 12px;
  padding: 0;
}

.toggle-password:hover {
  color: #2575fc;
}

/* 按钮组样式 */
.button-group {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

/* 注册按钮样式 */
.register-btn {
  padding: 12px;
  background: linear-gradient(135deg, #6a11cb, #2575fc);
  color: white;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: background 0.3s ease, transform 0.2s ease;
}

.register-btn:hover {
  background: linear-gradient(135deg, #2575fc, #6a11cb);
  transform: translateY(-2px);
}

.register-btn:active {
  transform: translateY(0);
}

/* 错误信息样式 */
.error {
  color: #ff4d4d;
  font-size: 12px;
  margin-top: 5px;
}

/* 动画 */
@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(-20px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>